package com.wm.orderService.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wm.commonutils.JwtUtils;
import com.wm.commonutils.R;
import com.wm.orderService.entity.Order;
import com.wm.orderService.service.OrderService;
import com.wm.servicebase.exceptionhandle.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author sshdg
 * @since 2020-10-13
 */
@RestController
@RequestMapping("/orderService/order")
//@CrossOrigin
@Api(tags = "订单管理")
public class OrderController {

    @Autowired
    OrderService orderService;

    @ApiOperation("生成订单")
    @PostMapping("/createOrder/{courseId}")
    public R createOrder(@PathVariable String courseId, HttpServletRequest request){

        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)){
            throw GuliException.from("请先登录！");
        }
        //创建订单，返回订单号
        String orderNo = orderService.createOrder(courseId, memberId);

        return R.ok().data("orderNo",orderNo);
    }

    @ApiOperation("根据订单id查询订单详情")
    @GetMapping("/getOrderInfo/{orderNo}")
    public R getOrderInfo(@PathVariable String orderNo){
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getOrderNo,orderNo);
        Order order = orderService.getOne(queryWrapper);
        return R.ok().data("order",order);
    }

    @ApiOperation("查询课程状态")
    @GetMapping("/isBuyCourse/{courseId}/{memberId}")
    public boolean isBuyCourse(@PathVariable String courseId,
                         @PathVariable String memberId){
        boolean isBuy = false;
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Order::getMemberId, memberId);
        wrapper.eq(Order::getCourseId, courseId);

        Order order = orderService.getOne(wrapper);

        if (!ObjectUtils.isEmpty(order) && order.getStatus() == 1){
            isBuy = true;
        }

        return isBuy;

    }
}

